package com.app.micaihu.view.user.usertask;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.infor.GetTaskBean;
import com.app.micaihu.bean.infor.UserTask;
import com.app.micaihu.bean.other.WebShareBean;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.components.ParamMap;
import com.app.widget.CommonTitle;
import com.app.widget.LoadView;
import com.app.micaihu.custom.view.web.CustomWebView;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.AndroidNativeShareUtils;
import com.app.micaihu.utils.AppShareUtils;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.utils.OkHttp3Helper;
import com.app.micaihu.view.user.userinfo.activity.WebActivity;
import com.app.utils.util.HelpUtils;
import com.app.utils.util.StringUtils;
import com.app.utils.util.ToastUtils;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.Utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by Guo on 2017/6/15.
 * <p>
 * <p>
 * 征兵的H5邀请页面
 */
@SuppressLint("JavascriptInterface")
public class ConscriptionRewardH5Activity extends BaseOldActivity implements View.OnClickListener {


    private String url;
    private CustomWebView webView;
    private FrameLayout flContent;
    private boolean isShowPageFinish = true;
    private JavascriptInterface javascriptInterface;
    private String uid;
    private int everyDayTaskType = -1;//每日邀请 的类型
    private boolean isOpenNativeShare = false;//是否已经到了 打开本地分享了
    private ProgressBar webViewProgressBar;

    private CommonTitle commonTitle;

    @Override
    protected void onResume() {
        super.onResume();
        DialogUtils.getInstance().dismissProgressDialog();
        //先判断是否登录
        if (UserInforManager.getInstance().isLogin()) {
            UserTask task = UserInforManager.getInstance().getUserInfor().getTask();
            if (!task.getInviteState() && isOpenNativeShare && everyDayTaskType >= 0) {//如果没有完成过
                isOpenNativeShare = false;
                if (webView != null) {
                    webView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            requestServerInviteData(String.valueOf(everyDayTaskType));
                        }
                    }, 1000);
                }

            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        DialogUtils.getInstance().dismissProgressDialog();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addContentView(R.layout.activity_web);
        Intent intent = this.getIntent();
        if (intent == null) return;
        url = intent.getStringExtra("url");
        uid = intent.getStringExtra("uid");
        setTitle("征兵");
        if (TextUtils.isEmpty(uid)) {
            TextView pageRightText = (TextView) findViewById(R.id.page_head_function_text);
            if (pageRightText != null) {
                pageRightText.setVisibility(View.GONE);
            }
        } else {
            setTitleRightText("我的士兵");
            TextView pageRightText = (TextView) findViewById(R.id.page_head_function_text);
            if (pageRightText != null) {
                pageRightText.setTextColor(AppApplication.getInstance().getResources().getColor(R.color.common_font_color_3));
                pageRightText.setOnClickListener(this);
            }
        }
        findViewById(R.id.mCommonTitle).setVisibility(View.GONE);
        flContent = findViewById(R.id.flContent);
        commonTitle = findViewById(R.id.mCommonTitle);
        webViewProgressBar = findViewById(R.id.webViewProgressBar);
        webView = new CustomWebView(Utils.getApp());
        flContent.addView(webView);

        initWebView();
        if (!TextUtils.isEmpty(url)) {
            String night = "0";
            if (url.contains("?")) {
                url += "&night=" + night;
            } else {
                url += "?night=" + night;
            }
            webView.loadUrl(url);
        } else {
            webView.loadUrl("about:blank");// 避免出现默认的错误界面
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        WebSettings settings = webView.getSettings();
//        settings.setBlockNetworkImage(true);// 延迟图片加载
        settings.setSavePassword(false);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowFileAccess(true);
        // 启动缓存
        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        // 设置缓存模式
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.setBackgroundColor(Color.argb(0, 0, 0, 0));
        //手动获取焦点
        webView.setFocusable(true);
        webView.setWebViewClient(new MyWebViewClient());
        webView.setWebChromeClient(new MyWebChromeClient());
        webView.requestFocus();
        if (Build.VERSION.SDK_INT >= 19) {
            settings.setLoadsImagesAutomatically(true);
        } else {
            settings.setLoadsImagesAutomatically(false);
        }
        javascriptInterface = new JavascriptInterface();

        webView.addJavascriptInterface(javascriptInterface, "android");

    }

    private class MyWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (!com.blankj.utilcode.util.StringUtils.isEmpty(title)) {
                commonTitle.setTitle(title);
            }
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                if (webViewProgressBar != null) {
                    webViewProgressBar.setVisibility(View.GONE);
                }
            } else {
                if (webViewProgressBar != null) {
                    webViewProgressBar.setVisibility(View.VISIBLE);
                    webViewProgressBar.setProgress(newProgress);
                }
            }
        }
    }

    /**
     * js 可调用的方法
     */
    @SuppressLint("JavascriptInterface")
    public class JavascriptInterface {

        WebShareBean webShareBean;//分享数据
        //        private ArrayList<File> shareFiles;
//        private ArrayList<File> shareFiles;
        private File[] files;

        //        1 2 3 :朋友圈/微信/qq
        private final int COPY_SUCESS = 2;//复制成功的code
        Handler handler = new Handler() {
            public void handleMessage(android.os.Message msg) {
                if (msg == null) {
                    return;
                }
                switch (msg.what) {
                    case 0://
                        WebShareBean shareBean = (WebShareBean) msg.obj;
                        if (shareBean == null) {
                            ToastUtils.makeText(getResources().getString(R.string.neterror));

                        } else {
                            if ("1".equals(shareBean.getShareType())) {//朋友圈
                                AppShareUtils.getInstance().setWXCShareContent(ConscriptionRewardH5Activity.this, webShareBean, umInviteListener);
                                everyDayTaskType = 3;
//                                downLoadImage(shareBean);
                            } else if ("2".equals(shareBean.getShareType())) {//微信
                                if (shareBean.getThumbList() != null && shareBean.getThumbList().size() > 0) {
                                    everyDayTaskType = 2;
                                    downLoadImage(shareBean);
                                } else {
                                    AppShareUtils.getInstance().setWXShareContent(ConscriptionRewardH5Activity.this, shareBean, umInviteListener);
                                }

                            } else if ("3".equals(shareBean.getShareType())) {//qq
                                if (shareBean.getThumbList() != null && shareBean.getThumbList().size() > 0) {
                                    everyDayTaskType = 4;
                                    downLoadImage(shareBean);
                                } else {
                                    AppShareUtils.getInstance().setQQShareContent(ConscriptionRewardH5Activity.this, shareBean, umInviteListener);
                                }
                            }
                        }
                        break;
                    case 1:
                        openNativaShare();
                        isOpenNativeShare = true;
                        break;
                    case COPY_SUCESS:
                        ToastUtils.makeText(R.drawable.handle_success, "已复制到粘贴板");
                        break;

                }


            }
        };


        /**
         * 下载图片
         */
        private void downLoadImage(WebShareBean webShareBean1) {
            this.webShareBean = webShareBean1;
            if (this.webShareBean == null
                    || this.webShareBean.getThumbList() == null
                    || this.webShareBean.getThumbList().isEmpty()) {
                openNativaShare();
                return;
            }
            DialogUtils.getInstance().showProgressDialog(ConscriptionRewardH5Activity.this, "图片处理中...");

            //创建一个 图片长度的数组
            files = new File[webShareBean.getThumbList().size()];

            final OkHttp3Helper.OnDownLoadResponCallBack onDownLoadResponCallBack = new OkHttp3Helper.OnDownLoadResponCallBack() {
                private int count = 0;

                @Override
                public void onStart() {

                }

                @Override
                public void onFailure() {
//                    shareFiles.add(null);
                    count++;
                    if (files != null && webShareBean != null &&
                            count == webShareBean.getThumbList().size()) {
                        handler.sendEmptyMessage(1);
                    }
                }

                @Override
                public void onSucess(File file) {
                    String name = file.getName();
                    int index = StringUtils.toInt(name.substring(0, 1), 0);
                    files[index] = file;
                    count++;
//                    shareFiles.add(file);
                    if (files != null && webShareBean != null &&
                            count == webShareBean.getThumbList().size()) {
                        handler.sendEmptyMessage(1);
                    }
                }
            };
            for (int i = 0; i < this.webShareBean.getThumbList().size(); i++) {
//                    String fileName = this.webShareBean.getThumbList().get(i).substring(this.webShareBean.getThumbList().get(i).lastIndexOf("/") + 1);
                String fileName = i + ".jpg";
                OkHttp3Helper.getInstance().downAsynFile(this.webShareBean.getThumbList().get(i),
                        AppConfigTools.USERSAVEIMG, fileName, onDownLoadResponCallBack);
            }
//            if (hasPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE})) {
//
//            } else {
//                requestRuntimePermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionListener() {
//                    @Override
//                    public void onGranted() {
//                        for (int i = 0; i < JavascriptInterface.this.webShareBean.getThumbList().size(); i++) {
////                            String fileName = JavascriptInterface.this.webShareBean.getThumbList().get(i).substring(JavascriptInterface.this.webShareBean.getThumbList().get(i).lastIndexOf("/") + 1) + ".jpg";
////                            String fileName = i + ".jpg";
//                            String fileName = i + ".jpg";
//                            OkHttp3Helper.getInstance().downAsynFile(JavascriptInterface.this.webShareBean.getThumbList().get(i),
//                                    AppConfigTools.USERSAVEIMG, fileName, onDownLoadResponCallBack);
//                        }
//                    }
//
//                    @Override
//                    public void onDenied(ArrayList<String> deniedList) {
//                        openNativaShare();
//                    }
//                });
//            }


        }


        public JavascriptInterface() {

        }

        @android.webkit.JavascriptInterface
        public void getData(String json) {
            WebShareBean shareBean = null;
            if (TextUtils.isEmpty(json)) {
                json = "";
            }
            Gson gson = new Gson();
            try {
                shareBean = gson.fromJson(json, WebShareBean.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Message msg = Message.obtain();
            msg.what = 0;
            msg.obj = shareBean;
            handler.sendMessage(msg);

        }


        @android.webkit.JavascriptInterface
        public void copy(String inviteCode) {
            HelpUtils.copy(inviteCode, AppApplication.getInstance());
            handler.sendEmptyMessage(COPY_SUCESS);
        }


        /**
         * 打开原生分享
         */
        private void openNativaShare() {

            DialogUtils.getInstance().showProgressDialog(ConscriptionRewardH5Activity.this, "分享跳转中,请稍候");
            if (webShareBean == null) {
                ToastUtils.showText("分享失败,请重试");
                return;
            }

            if ("1".equals(webShareBean.getShareType())) {//朋友圈
                if (files == null || files[0] == null) {
                    new AndroidNativeShareUtils(ConscriptionRewardH5Activity.this).shareWeChatFriendCircle(
                            webShareBean.getShareTitle(),
                            webShareBean.getShareSummary(), "", "收徒朋友圈点击");
                } else {
                    ArrayList<File> fileList = new ArrayList<>();
                    for (File file :
                            files) {
                        if (file != null && file.exists() && file.isFile()) {
                            fileList.add(file);
                        }
                    }
                    if (fileList.size() > 0) {
                        new AndroidNativeShareUtils(ConscriptionRewardH5Activity.this).shareWeChatFriendCircle(
                                webShareBean.getShareTitle(),
                                webShareBean.getShareSummary(), fileList, "收徒朋友圈点击");
                    }
                }
            } else if ("2".equals(webShareBean.getShareType())) {//微信
                if (files != null && files[0] != null) {
//                    new AndroidNativeShareUtils(ConscriptionRewardH5Activity.this).shareImage(files[0].getAbsolutePath());

                    new AndroidNativeShareUtils(ConscriptionRewardH5Activity.this).shareWeChatFriend("", "", AndroidNativeShareUtils.DRAWABLE, files[0].getAbsolutePath(), "收徒微信点击");
                }
            } else if ("3".equals(webShareBean.getShareType())) {//qq
                if (files != null && files[0] != null) {
                    new AndroidNativeShareUtils(ConscriptionRewardH5Activity.this).shareQQFriend("", "", AndroidNativeShareUtils.DRAWABLE, files[0].getAbsolutePath(), "收徒qq点击");

                }
            }


        }

    }


    /**
     * 邀请后的回调
     */
    public UMShareListener umInviteListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            ToastUtils.makeText(R.drawable.handle_success, "分享成功");
            StatisticInvite(platform);
            StatService.onEvent(mActivity, "010", "邀请好友成功", 1);//统计事件的点击次数
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtils.makeText(R.drawable.handle_fail, "分享失败");
            StatService.onEvent(mActivity, "011", "邀请好友失败", 1);//统计事件的点击次数
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtils.makeText("分享取消");
        }

    };

    /**
     * 统计邀请次数
     *
     * @param platform 平台号
     */
    private void StatisticInvite(SHARE_MEDIA platform) {
        if (platform == null) {
            ToastUtils.makeText(R.drawable.handle_fail, "分享失败");
            return;
        }

        String type = "0";
        if (SHARE_MEDIA.SINA.equals(platform.toSnsPlatform().mPlatform)) {
            type = "1";
        } else if (SHARE_MEDIA.WEIXIN.equals(platform.toSnsPlatform().mPlatform)) {
            type = "2";
        } else if (SHARE_MEDIA.WEIXIN_CIRCLE.equals(platform.toSnsPlatform().mPlatform)) {
            type = "3";
        } else if (SHARE_MEDIA.QQ.equals(platform.toSnsPlatform().mPlatform)) {
            type = "4";
        } else if (SHARE_MEDIA.QZONE.equals(platform.toSnsPlatform().mPlatform)) {
            type = "5";
        } else {
            type = "0";
        }
        requestServerInviteData(type);
    }


    /**
     * 刷新服务器 邀请数据
     *
     * @param type
     */
    private void requestServerInviteData(String type) {
        ParamMap param = new ParamMap();
        param.putEncode("channelType", type);
        if (UserInforManager.getInstance() != null) {
            param.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
        } else {
            param.putEncode("uid", "");
        }
        HttpUtils.ParmsMapMD5(param);

        HttpListener httpListener = new HttpListener<DataBean<GetTaskBean>>() {
            @Override
            public void onError(VolleyError error) {
            }

            @Override
            public void onSuccess(DataBean<GetTaskBean> response) {
                if (response.noError() && response.getData() != null
                        && response.getData().getIsGetTask("邀请好友")) {
                    //刷新任务
                    UserInforManager.getInstance().getUserTask(mActivity, false);
                }
            }
        };

        addPostRequest(URIContant.INVITE_COUNT, new TypeToken<DataBean<GetTaskBean>>() {
        }.getType(), param, httpListener);
    }


    // 监听
    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, com.tencent.smtt.export.external.interfaces.SslError sslError) {
            sslErrorHandler.proceed();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (TextUtils.isEmpty(url) || url.length() < 5) {
                return false;
            }
            //判断是否为http协议，如果是自定义协议则交给系统
            String httpStr = "";
            try {
                httpStr = url.substring(0, 4);
            } catch (Exception e1) {
                e1.printStackTrace();
                return false;
            }
            if (!TextUtils.isEmpty(httpStr) && !httpStr.equals("http")
                    && !httpStr.equals("https") && !httpStr.equals("abou")) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                try {
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            } else if (httpStr.equals("abou")) {
                return true;
            } else {
                if (view != null) {
                    view.loadUrl(url);
                }
                return true;
            }


        }

        @Override
        public void onPageFinished(final WebView view, String url) {
//            view.getSettings().setBlockNetworkImage(false);// 取消延迟加载

            if (isShowPageFinish) {
                isShowPageFinish = false;
                if (!view.getSettings().getLoadsImagesAutomatically()) {
                    view.getSettings().setLoadsImagesAutomatically(true);
                }
            }

        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            if (url != null && url.equals(failingUrl)) {
                isShowPageFinish = false;
            }
            super.onReceivedError(view, errorCode, description, failingUrl);


        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //设置友盟回调
        try {
            if (data != null) {
                UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.destroy();
        }
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        if (v == null) return;
        switch (v.getId()) {
            case R.id.error_page://loadview的错误页面ID
                //刷新
                if (TextUtils.isEmpty(url)) {
                    ToastUtils.showText("加载的网址为空");
                    return;
                }
                if (webView == null) {
                    return;
                }
                webView.clearHistory();
                isShowPageFinish = true;
                webView.loadUrl(url);
                break;
            case R.id.page_head_function_text:
                if (!TextUtils.isEmpty(uid)) {

                    try {
                        Intent intent = new Intent(mActivity, WebActivity.class);
                        intent.putExtra("title", "我的士兵");
                        intent.putExtra("url", URIContant.TASK_CONSCRIPTION_MYSOLOIDER + uid);

                        mActivity.startActivity(intent);
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                break;
        }
    }
}
